package com.future.myapplication

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import android.telephony.SmsManager
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import java.io.BufferedReader
import java.io.InputStreamReader


class MainActivity : AppCompatActivity() {
    private val SEND_SMS = 100
    private val SEND_SMS1 = 101
    private val SEND_SMS2 = 102
    private val content: String = "测试短信发送！！！！"
    private var adapter: AdapterList? = null
    var logs: String? = ""
    var list: ArrayList<PhoneBean> = arrayListOf()//创建一个空的对象
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        requestPermission()
        getFromAssets("text.txt")

        val layoutManager = LinearLayoutManager(this)
        recycleView.layoutManager = layoutManager
        adapter = AdapterList(list)
        recycleView.adapter = adapter
        adapter?.notifyDataSetChanged()

        var index = 0
        btn.setOnClickListener {
            GlobalScope.launch(Dispatchers.IO) {
                repeat(list.size) {
                    GlobalScope.launch(Dispatchers.Main) {
                        sendSMSS(list[index])
                    }
                    delay(10000)
                    index++
                }
                index = 0
            }
        }
    }

    private fun requestPermission() {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission =
                ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.SEND_SMS),
                    SEND_SMS
                )
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE),
                    SEND_SMS1
                )
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    SEND_SMS2
                )
                return
            }
        }
    }

    /**
     * 注册权限申请回调
     *
     * @param requestCode  申请码
     * @param permissions  申请的权限
     * @param grantResults 结果
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            SEND_SMS -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//                sendSMSS()
            } else {
                // Permission Denied
                showToast("手机权限没有给！！")
                Toast.makeText(this@MainActivity, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions!!, grantResults)
        }
    }


    //发送短信
    private fun sendSMSS(bean: PhoneBean) {
        if (!TextUtils.isEmpty(content) && !TextUtils.isEmpty(bean.phone)) {
            val manager: SmsManager = SmsManager.getDefault()
            val strings: ArrayList<String> = manager.divideMessage(content)
            for (i in 0 until strings.size) {
                manager.sendTextMessage(bean.phone, null, content, null, null)
            }
            modeData(bean, true)
            showToast("发送成功")
        } else {
            showToast("发送失败")
            modeData(bean, false)
            return
        }
        adapter?.notifyDataSetChanged()
    }

    private fun modeData(bean: PhoneBean, boolean: Boolean) {
        for ((index, e) in list.withIndex()) {
            if (bean == list[index]) {
                list[index].isStatus = boolean
            }
        }
    }

    /**
     * 根据行数读取文件
     */
    private fun getFromAssets(fileName: String?): String? {
        try {
            val inputReader = InputStreamReader(resources.assets.open(fileName!!))
            val bufReader = BufferedReader(inputReader)
            var line: String? = ""
            var Result: String? = ""
            while (bufReader.readLine().also { line = it } != null) {
                Result += line
                list.add(PhoneBean(line))
            }
            showToast("手机号码列表加载完毕！！")
            return Result
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return null
    }

    private fun showToast(content: String) {
        Toast.makeText(this@MainActivity, content, Toast.LENGTH_SHORT).show()
    }
}